// pages/qrcode/qrcode.html.js
const app = getApp()
import base64 from '../../utils/base'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide:false,
    hasUserInfo: false,
    isuserbind: false,
    inputusername: '',
    inputpassword: '',
    disabled:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(query) {
    const href = decodeURIComponent(query.q);
    // const href='https://njust.jiaozuoye.online/check?d=testId&t=1500&m=135d81a3952ec923c013b4e1e1ae6abb&ts=1698649221221'
    const params = this.getUrlVars(href);
    let serverHostNoPort=href.split('/')[2];
    app.globalData.checkin_url=serverHostNoPort;
    const deviceId=params.d;
    const timestamp=params.t;
    const md5_timestamp=params.m;
    // const deviceId='101';
    // const timestamp='1000';
    // const md5_timestamp='78392bdc6d8ddead057c04f070833463';
    const that=this;
    wx.request({
      url: `https://${app.globalData.checkin_url}/door/wechat_checkin?d=${deviceId}&t=${timestamp}&m=${md5_timestamp}`,
      method: 'post',
      header: {
        'content-type': 'application/json'
      },
      success: res => {
        const data=res.data;
        if(data.task==='error'){
            return  wx.showToast({
              title: '签到失败：'+data.info,
              icon: 'none',
              duration: 2000
            })
        }else{
          const room=data.room;
          app.globalData.room=room
          that.getUserInfo()
        }
      }
    })
  },

  getUrlVars(href) {
    var vars = [], hash;
    const begin=href.indexOf('?') + 1;
    const last=href.indexOf('#');
    const end=(last>-1)?last:undefined;
    var hashes = href.slice(begin,end).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
},

  getUserInfo(){
    const that=this;
    wx.getSetting({
      success: function(res) {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function(res) {
                  app.globalData.userInfo = res.userInfo;
                  that.wxLogin()
                 }})
          }else {
            // 用户没有授权
            // 改变 isHide 的值，显示授权页面
            that.setData({
                isHide: true
            });
        }
        }
      }
      )
  },
  bindGetUserInfo(e){
    console.log(e.detail.userInfo)
    if (e.detail.userInfo) {
      // 获取到用户的信息了，打印到控制台上看下
      app.globalData.userInfo = e.detail.userInfo;
      this.wxLogin()
    }else {
      //用户按了拒绝按钮
      wx.showModal({
          title: '警告',
          content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
          showCancel: false,
          confirmText: '返回授权',
          success: function(res) {
              // 用户没有授权成功，不需要改变 isHide 的值
              if (res.confirm) {
                  console.log('用户点击了“返回授权”');
              }
          }
      });
  }
  },
  wxLogin(){
    wx.login({
      success: res => {
          wx.request({
            url: `https://${app.globalData.checkin_url}/wechat/get_xcx_user?code=${res.code}`,
            method: 'get',
            header: {
              'content-type': 'application/json'
            },
            success: res2 => {
              console.log("res2",res2)
              if(res2.statusCode===200){
                const result=res2.data.result;
                  const unionid=result.unionid;
                  app.globalData.unionid=unionid;
                  //已绑定用户调用签到接口
                  if (!res2.data.user) {
                    app.globalData.localuserinfo = {};
                    this.setData({
                      isuserbind: false,
                      localinfo: "",
                      loading: false
                    })
                  } else {
                    var localuserinfo = res2.data.user;
                    app.globalData.localuserinfo=res2.data.user;
                    this.setData({
                      isuserbind: true,
                      localinfo: "用户名:" + localuserinfo.username + " ，名字:" + localuserinfo.showName,
                      loading: false
                    })
                      wx.redirectTo({
                        url: '../checkin/checkin',
                        fail:res=>{
                          console.log("fail");
                          console.log(res);
                        },
                      })
                  }
              }
            },
            fail:res=>{
              console.log("fail");
              console.log(res);
            },
          })
      }})
      this.setData({
        isHide: false
    });
  },
  bindKeyInput: function (e) {
    this.setData({
      inputusername: e.detail.value
    })
  },
  bindKeypasswordInput: function (e) {
    this.setData({
      inputpassword: e.detail.value
    })
  },
  bind: function () {
    var that = this;
     if (this.data.inputusername == "" || this.data.inputpassword == "") {
      wx.showToast({
        title: '请填写交作业系统用户登录名及密码',
        icon: 'none',
        duration: 2000
      })
    } else {
      that.setData({
        loading:true
      })
      wx.request({
        url: 'https://'+app.globalData.checkin_url+'/api/v1/login',
        data: {
          username: this.data.inputusername,
          password: this.data.inputpassword
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: res => {
          if (res.data.error) {
            wx.showToast({
              title: res.data.error,
              icon: 'none',
              duration: 2000
            })
            this.setData({
              isuserbind: false,
              localinfo: "",
              loading:false
            })
          } else {
            var localuserinfo = res.data;
            app.globalData.localuserinfo = localuserinfo;
            const sessionKey=base64.base64Encode(app.globalData.access_key);
            wx.request({
              url: 'https://'+app.globalData.checkin_url +'/wechat/bind_unionid_to_user',
              data: {
                unionid: app.globalData.unionid,
                username: this.data.inputusername,
                session_key:sessionKey
              },
              method: 'POST',
              header: {
                'content-type': 'application/json'
              },
              success: res => {
                console.log("res.data",res.data)
                if (res.data.status == 'fail') {
                  app.globalData.localuserinfo = {};
                  this.setData({
                    isuserbind: false,
                    localinfo: "",
                    loading: false
                  })
                } else {
                  var localuserinfo = res.data;
                  this.setData({
                    isuserbind: true,
                    localinfo: "用户名:" + localuserinfo.username + " ，名字:" + localuserinfo.showName,
                    loading: false
                  })
  
                    wx.redirectTo({
                      url: '../checkin/checkin',
                      fail:res=>{
                        console.log("fail");
                        console.log(res);
                      },
                    })
                }
              }
            })
          }
        },
        fail:res=>{
          console.log("login fail")
          //console.log(res);
          wx.showToast({
            title: "连接服务器出错，绑定失败",
            icon: 'none',
            duration: 2000
          })
          that.setData({
            loading: false
          })
        }
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})